﻿using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using NewRetail.Application.Components.Platform;
using NewRetail.Application.Components.Platform.Entity;
using NewRetail.Application.Components.PrintTask;
using NewRetail.Application.Components.PrintTask.Model;
using NewRetail.Application.Core;
using System;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;

namespace NewRetail.Api.Controllers
{
    [NewRetailRoute("pos-cashier")]
    public class PosCashierController : BaseController<PosCashier>
    {
        private readonly IPosCashierService posCashierService;
        private readonly IPrintAuthorizationCodeTaskService printAuthorizationCodeTaskService;
        public PosCashierController(IPosCashierService posCashierService, IPrintAuthorizationCodeTaskService printAuthorizationCodeTaskService)
        {
            this.posCashierService = posCashierService;
            this.printAuthorizationCodeTaskService = printAuthorizationCodeTaskService;
        }

        public override async Task<ResponseEntity<PagedResultDto<PosCashier>>> QueryPaging([FromBody] PagingRequestDto dto)
        {
            var data = await base.QueryPaging(dto);

            if (data.Data?.Items?.Any() ?? false)
            {
                data.Data.Items = await this.posCashierService.AttachWarehouse(data.Data.Items.ToArray());
            }

            return data;
        }

        public override Task<ResponseEntity<PosCashier>> Save([FromBody] PosCashier data)
        {
            data.password.Should().NotBeNullOrEmpty();

            if (data.password.Length < 30)
            {
                data.password = data.password.ToMd5();
            }

            return base.Save(data);
        }

        [HttpPost("save-print-authorization-code-task")]
        public async Task<ResponseEntity<string>> SavePrintAuthorizationCodeTask([FromBody] PrintAuthorizationCodeTaskSaveInputDto dto)
        {
            dto.Should().NotBeNull();
            dto.cashierName.Should().NotBeNullOrEmpty();
            dto.authorizationCode.Should().NotBeNullOrEmpty();
            dto.warehouseId.Should().NotBeNullOrEmpty();

            var ret = new ResponseEntity<string>();
            try
            {
                var result = await this.printAuthorizationCodeTaskService.SavePrintAuthorizationCodeTaskItems(dto);
                if (result.Item1 == 0)
                    ret.SetError("创建打印任务失败！" + result.Item2);
                ret.SetData("创建打印任务成功");
            }
            catch (Exception e)
            {
                ret.SetError("创建失败！" + e.Message);
            }

            return ret;
        }
    }
}
